package com.shchekoldin.server.rest;

import com.shchekoldin.server.dto.MercurialBranchDto;
import com.shchekoldin.server.presenter.MercurialBranchPresenter;
import com.shchekoldin.server.service.JiraService;
import com.shchekoldin.server.service.MercurialService;
import com.sun.jersey.spi.resource.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.swift.common.soap.jira.RemoteIssue;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.ArrayList;
import java.util.List;

@Singleton
@Path("/branch")
@Produces(MediaType.APPLICATION_JSON)
public class BranchRestService {

    private static final Logger LOGGER = LoggerFactory.getLogger(BranchRestService.class);

    // -------------------------------------------------------
    // LOGIC
    // -------------------------------------------------------

    //
    // API
    //

    @GET
    @Path("/list/{firstResult}/{maxResults}/")
    public List<MercurialBranchPresenter> getList(@PathParam("firstResult") int firstResult,
        @PathParam("maxResults") int maxResults) throws Exception {
        List<MercurialBranchDto> branches = MercurialService.INSTANCE.run(firstResult, maxResults);

        if (branches.size() == 0) {
            LOGGER.error("Branches list is empty");
            throw new WebApplicationException();
        }

        RemoteIssue[] issues = JiraService.INSTANCE.run(branches);
        List<MercurialBranchPresenter> result = new ArrayList<MercurialBranchPresenter>(branches.size());

        for (MercurialBranchDto branch : branches) {
            if (!branch.isKeyValid()) {
                result.add(new MercurialBranchPresenter(branch, null));
                continue;
            }

            for (RemoteIssue issue : issues) {
                if (branch.getKey().equals(issue.getKey())) {
                    result.add(new MercurialBranchPresenter(branch, issue));
                    break;
                }
            }
        }

        return result;
    }

}
